#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <strings.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>

#include "api/api.h"

struct termios oldtio;

int main(int argc, char* argv[])
{
	printf("SENDER: APPLICATION STARTED\n");
	
	if( argc != 2 ) { // TODO complete
		printf("ERROR: usage: sender <port_number> <file_path>\n");
		return EXIT_FAILURE;
	}
	
	int file_fd = open(argv[1], O_RDONLY); // TODO file to transfer by argv[2]
	
	if (file_fd < 0) {
		perror("SENDER: \n");
		exit(errno);
	}
	int fd = llopen(TTYS0, SENDER); // TODO serial port number by argv[1]
	
		
	char buf[DATA_SIZE];
	int total_bytes = 0;
	int bytes_read = -1;
	
	llwrite(fd, argv[1], START_CONTROL_PACKET);
	
	while(bytes_read != 0)
	{
		bzero(&buf, DATA_SIZE);
		bytes_read = read(file_fd,&buf,DATA_SIZE);
		if(bytes_read == EOF)
			break; //end of reading file
		if(bytes_read < 0)
		{
			printf("ERROR READING FILE: errno = %d\n", errno);
			return EXIT_FAILURE; 
		}
		total_bytes += bytes_read;
		if(llwrite(fd,buf,bytes_read) != bytes_read)
			printf("ZOMG BYTES != BYTES!!!\n");
	}
	
	//escrever pacote de terminar transmissao
	llwrite(fd, (char*) &file_fd, END_CONTROL_PACKET);
	
	llclose(fd);
	
	printf("File sent! Bye bye\n");
	
	return 0;
}

